const net = require('net');

const socket = new net.Socket({});

socket.connect({
  host: '127.0.0.1',
  port: 4000
});

const lessonids = [
  "136797",
  "136798",
  "136799",
  "136800",
  "136801",
  "136803",
  "136804",
  "136806",
  "136807",
  "136808",
  "136809",
  "141994",
  "143517",
  "143557",
  "143564",
  "143644",
  "146470",
  "146569",
  "146582"
];

let id = Math.floor(Math.random() * lessonids.length)
  , buffer;

socket.on('data', (buffer) => {
  const seqBuffer = buffer.slice(0, 2);
  const titleBuffer = buffer.slice(2);

  console.log(seqBuffer.readInt16BE());
  console.log(titleBuffer.toString());
});

// 把编码请求包的逻辑封装为一个函数
let seq = 0;
function encode(index) {
  buffer = Buffer.alloc(6);
  buffer.writeInt16BE(seq);
  buffer.writeInt32BE(
    lessonids[index],
    2
  );
  console.log(seq, lessonids[index]);
  seq++;
  return buffer;
}

往服务器传数据
setInterval(() => {
  socket.write(encode(id));
}, 50);

/** tcp会进行粘包
 * 这里for循环里反复调用socket.write
 * 并不会每次都向服务器写入,而是会等循环完,把循环写入的内容统一发给服务端
 * 你可以通过在服务端ondata打印接受到的buffer来验证*/
// for(let i=0;i<100;++i) {
//   id = Math.floor(Math.random() * lessonids.length);
//   socket.write(encode(id));
// }
